﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Data.SQLite;
using System.Linq;
using System.Windows.Shapes;
using WPF_PathSearchUtil.entity;
using WPF_PathSearchUtil.service;
using WPF_PathSearchUtil.utils;
using System.Windows;

namespace WPF_PathSearchUtil.data_access
{
    public class LocalClient : CSVReadOrWrite
    {
        /// <summary>
        /// 根据文件路径读取文件内容
        /// </summary>
        /// <param name="items"> imPath：导入文件路径</param>
        /// <returns>成功：返回 画面用list，失败：返回 字符串</returns>
        public Resp Read(params object[] items)
        {
            String imPath = null;
            ObservableCollection<ObservableCollection<String>> fileListStr = new ObservableCollection<ObservableCollection<string>>();
            foreach (object item in items)
            {
                if (item is string)
                {
                    imPath = (string) item;
                }
            }
            if (!File.Exists(imPath))
            {
                return Resp.Fail("文件不存在。");
            }
            String connstr = "Data source=" + imPath + ";version=3;";
            try
            {
                using (var conn = new System.Data.SQLite.SQLiteConnection(connstr))
                {
                    conn.Open();
                    var select = "SELECT fileName,filePath,fileType,fileSize,fileDate from FileInfos";
                    using (var sc = new SQLiteCommand(select, conn))
                    {
                        var sr = sc.ExecuteReader();
                        while (sr.Read())
                        {
                            ObservableCollection<String> strings = new ObservableCollection<String>
                            {
                                sr.GetString(0),
                                sr.GetString(1),
                                sr.GetString(2),
                                sr.GetString(3),
                                sr.GetString(4)

                            };
                            fileListStr.Add(strings);
                        }
                    }
                }
            }
            catch
            {
                return Resp.Fail("数据格式有误。");
            }
            return Resp.Success(fileListStr);
        }

        /// <summary>
        /// 根据目录路径，保存db文件
        /// </summary>
        /// <param name="items">exPath：导出的目录，fileListStr：导出的列表</param>
        /// <returns>成功：返回文件路径，失败：返回字符串</returns>
        public Resp Write(params object[] items)
        {
            String exPath = null;
            ObservableCollection<ObservableCollection<String>> fileListStr = null;
            foreach (object item in items)
            {
                if (item is string)
                {
                    exPath = (string)item;
                    continue;
                }
                if (item is ObservableCollection<ObservableCollection<String>>)
                {
                    fileListStr = (ObservableCollection<ObservableCollection<String>>)item;
                    continue;
                }
            }
            if (!Directory.Exists(exPath))
            {
                try
                {
                    Directory.CreateDirectory(exPath);
                }
                catch
                {
                    return Resp.Fail("导出目录不存在。");
                }
            }
            if (exPath.LastIndexOf("\\") != exPath.Length - 1)
            {
                exPath += "\\";
            }
            String filePath = exPath + System.DateTime.Now.ToString().Replace(":", "-").Replace("/", "-") + " CSVResult.db";
            //String filePath = exPath + "Result.db";
            String connstr = "Data source=" + filePath;
            using (var conn = new SQLiteConnection(connstr))
            {
                conn.Open();
                var createTable = @"CREATE TABLE IF NOT EXISTS FileInfos(
                                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                                        fileName TEXT,
                                        filePath TEXT,
                                        fileType TEXT,
                                        fileSize TEXT,
                                        fileDate TEXT)";
                using (var ctc = new SQLiteCommand(createTable, conn))
                {
                    ctc.ExecuteNonQuery();
                }
                var clear = "delete from FileInfos";
                using (var cc = new SQLiteCommand(clear, conn))
                {
                    cc.ExecuteNonQuery();
                }
                foreach (var fileInfo in fileListStr)
                {

                    var insert = @"INSERT INTO FileInfos(fileName,filePath,fileType,fileSize,fileDate)
                                                VALUES(@Name,@Path,@Type,@Size,@Date)";
                    using (var ic = new SQLiteCommand(insert, conn))
                    {
                        ic.Parameters.AddWithValue("@Name", fileInfo[0]);
                        ic.Parameters.AddWithValue("@Path", fileInfo[1]);
                        ic.Parameters.AddWithValue("@Type", fileInfo[2]);
                        ic.Parameters.AddWithValue("@Size", fileInfo[3]);
                        ic.Parameters.AddWithValue("@Date", fileInfo[4]);
                        ic.ExecuteNonQuery();
                    }
                }
            }
            return Resp.Success(filePath);
        }

    }
}
